package com.inkwell.internet.productregistration.registration.portlet;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;

import com.inkwell.internet.productregistration.model.PRRegistration;
import com.inkwell.internet.productregistration.model.PRUser;
import com.inkwell.internet.productregistration.model.impl.PRRegistrationImpl;
import com.inkwell.internet.productregistration.model.impl.PRUserImpl;
import com.inkwell.internet.productregistration.service.PRRegistrationLocalServiceUtil;
import com.inkwell.internet.productregistration.service.PRUserLocalServiceUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.util.CalendarFactoryUtil;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.Address;
import com.liferay.portal.model.User;
import com.liferay.portal.service.AddressLocalServiceUtil;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.util.bridges.mvc.MVCPortlet;

public class ProductRegistrationPortlet extends MVCPortlet {

	private String viewAddRegistrationJSP = "/registration/view_add_registration.jsp";
	private String viewThankYouJSP = "/registration/view_thank_you.jsp";

	public void addRegistration(ActionRequest request, ActionResponse response) {

		ThemeDisplay themeDisplay = (ThemeDisplay) request
				.getAttribute(WebKeys.THEME_DISPLAY);

		PRRegistration prRegistration = new PRRegistrationImpl();
		PRUser prUser = new PRUserImpl();

		if (themeDisplay.isSignedIn()) {
			User user = themeDisplay.getUser();

			List<Address> addresses = Collections.EMPTY_LIST;
			Address homeAddr = null;

			try {
				addresses = AddressLocalServiceUtil.getAddresses(
						user.getCompanyId(), User.class.getName(),
						user.getUserId());
			} catch (SystemException e) {
				System.out.println(e);
			}

			if (addresses.size() > 0) {
				homeAddr = addresses.get(0);
			}

			prUser.setFirstName(user.getFirstName());
			prUser.setLastName(user.getLastName());
			prUser.setEmail(user.getEmailAddress());

			try {
				prUser.setBirthDate(user.getBirthday());
				boolean male = user.getMale();
				if (male)
					prUser.setGender("male");
				else
					prUser.setGender("female");
			} catch (PortalException e) {
				// TODO Auto-generated catch block
				prUser.setBirthDate(new Date());
			} catch (SystemException e) {
				// TODO Auto-generated catch block
				prUser.setGender("male");
			}

			if (homeAddr != null) {
				prUser.setAddress1(homeAddr.getStreet1());
				prUser.setAddress2(homeAddr.getStreet2());
				prUser.setCity(homeAddr.getCity());
				prUser.setPostalCode(homeAddr.getZip());
				prUser.setCountry(homeAddr.getCountry().toString());
			}

			prRegistration.setDatePurchased(new Date());
		} else {
			prRegistration.setDatePurchased(new Date());
			Calendar dob = CalendarFactoryUtil.getCalendar();
			dob.set(Calendar.YEAR, 1970);
			prUser.setBirthDate(dob.getTime());
			prUser.setGender("");
		}

		request.setAttribute("regUser", prUser);
		request.setAttribute("registration", prRegistration);
		response.setRenderParameter("jspPage", viewAddRegistrationJSP);
	}

	public void registerProduct(ActionRequest request, ActionResponse response)
			throws Exception {
				
		PRUser regUser = ActionUtil.prUserFromRequest(request);
		PRRegistration registration = ActionUtil
				.prRegistrationFromRequest(request);

		ThemeDisplay themeDisplay = (ThemeDisplay) request
				.getAttribute(WebKeys.THEME_DISPLAY);
		long userId = themeDisplay.getUserId();
		
		System.out.println("userid:"+userId);

		User liferayUser = UserLocalServiceUtil.getUser(userId);

		ArrayList<String> errors = new ArrayList<String>();

		boolean validUser = ProdRegValidator.validateUser(regUser, errors);
		boolean validRegister = ProdRegValidator.validateRegistration(
				registration, errors);

		if (validUser && validRegister) {
			PRUser user = null;

			if (liferayUser.isDefaultUser()) {
				userId = 0;
				user = PRUserLocalServiceUtil.addPRUser(regUser, userId);
			} else {
				user = PRUserLocalServiceUtil.getPRUser(themeDisplay.getScopeGroupId(),userId);

				if (user == null) {
					regUser.setUserId(userId);
					user = PRUserLocalServiceUtil.addPRUser(regUser, userId);
				}
			}

			registration.setPrUserId(user.getPrUserId());
			PRRegistrationLocalServiceUtil.addRegistration(registration);
			SessionMessages.add(request, "registration-saved-successfully");
			response.setRenderParameter("jspPage", viewThankYouJSP);
		} else {
			for (String error : errors) {
				SessionErrors.add(request, error);
			}
			SessionErrors.add(request, "error-saving-registration");
			response.setRenderParameter("jspPage", viewAddRegistrationJSP);
			request.setAttribute("regUser", regUser);
			request.setAttribute("registration", registration);
		}
	}
}
